// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package traffic

import (
	"apiote.xyz/p/szczanieckiej/transformers"

	"bufio"
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"time"

	"golang.org/x/text/transform"
)

type KrakowZtpT struct{}

func (KrakowZtpT) getTimezone() *time.Location {
	l, _ := time.LoadLocation("Europe/Warsaw")
	return l
}

func (KrakowZtpT) ConvertVehicles() ([]Vehicle, error) {
	return []Vehicle{}, nil
}

func (f KrakowZtpT) GetVersions(date time.Time, timezone *time.Location) ([]Version, error) {
	startDate := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, timezone)
	endDate := time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 0, timezone)
	v := Version{
		Link:      "https://gtfs.ztp.krakow.pl/GTFS_KRK_T.zip",
		ValidFrom: startDate,
		ValidTill: endDate,
	}
	return []Version{v}, nil
}

func (KrakowZtpT) RealtimeFeeds() map[RealtimeFeedType]string {
	return map[RealtimeFeedType]string{
		ALERTS:            "https://gtfs.ztp.krakow.pl/ServiceAlerts_T.pb",
		TRIP_UPDATES:      "https://gtfs.ztp.krakow.pl/TripUpdates_T.pb",
		VEHICLE_POSITIONS: "https://gtfs.ztp.krakow.pl/VehiclePositions_T.pb",
	}
}

func (KrakowZtpT) String() string {
	return "krakow_ztp_t"
}

func (z KrakowZtpT) Transformer() transform.Transformer {
	return transformers.TransformerPL
}

func (z KrakowZtpT) Name() string {
	return "ZTP Kraków Tram"
}

func (z KrakowZtpT) Flags() FeedFlags {
	return FeedFlags{
		Headsign:     HeadsignTripHeadsing,
		StopIdFormat: "{{stop_id}}",
		StopName:     "{{stop_name}}",
		LineName:     "{{route_short_name}}",
	}
}

func (z KrakowZtpT) FeedPrepareZip(path string) error {
	// NOTE fix route types
	routesFile, err := os.Open(filepath.Join(path, "routes.txt"))
	if err != nil {
		return fmt.Errorf("while opening routes file: %w", err)
	}
	defer routesFile.Close()
	routes2File, err := os.OpenFile(filepath.Join(path, "routes2.txt"), os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		return fmt.Errorf("while opening routes2 file: %w", err)
	}
	defer routes2File.Close()
	r := csv.NewReader(bufio.NewReader(routesFile))
	w := csv.NewWriter(routes2File)
	header, err := r.Read()
	if err != nil {
		return fmt.Errorf("while reading routes header: %w", err)
	}
	fields := map[string]int{}
	for i, headerField := range header {
		fields[headerField] = i
	}
	err = w.Write(header)
	if err != nil {
		return fmt.Errorf("while writing routes header: %w", err)
	}

	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			return fmt.Errorf("while reading a route record: %w", err)
		}
		if record[fields["route_type"]] == "900" {
			record[fields["route_type"]] = "0"
		}
		err = w.Write(record)
		if err != nil {
			return fmt.Errorf("while writing a route record: %w", err)
		}
	}
	w.Flush()
	err = os.Remove(filepath.Join(path, "routes.txt"))
	if err != nil {
		return fmt.Errorf("while removing routes: %w", err)
	}
	err = os.Rename(filepath.Join(path, "routes2.txt"), filepath.Join(path, "routes.txt"))
	if err != nil {
		return fmt.Errorf("while renaming routes: %w", err)
	}
	return nil
}

func (z KrakowZtpT) QRInfo() (string, QRLocation, string) {
	return "", QRLocationNone, ""
}
